<script lang="ts">
	import { onMount, onDestroy } from 'svelte'
	import { Chart, registerables } from 'chart.js/auto'
	import 'chartjs-adapter-luxon'
	import 'chartjs-adapter-date-fns' // 这个一定要引入，不然[chartjs-chart-financial]会报错
	import 'chartjs-chart-financial'
	import { CandlestickElement, CandlestickController } from 'chartjs-chart-financial'

	import zoomPlugin from 'chartjs-plugin-zoom'
	import { Tabs, TabItem } from 'flowbite-svelte'
	import { UserCircleSolid } from 'flowbite-svelte-icons'
	import SecuritySetting from './SecuritySetting.svelte'
	import IndicatorsCombination from './IndicatorsCombination.svelte'
	import {
		CandleChartConfig,
		IndicatorChartConfig,
		upsertChartPrice,
		upsertChartTrendLine,
		upsertChartVolume,
	} from './SecurityChartConf'
	import type { Unsubscriber } from 'svelte/store'
	import {
		indicatorYaxisStore,
		klineResultStore,
		setIndicatorChartYaxises,
		trendLineStore,
	} from './FudaStore'
	import type { IndicatorGroupKey, KlineFlat } from './bindings'
	import { formatDate } from '$lib'
	import {
		handleChartMouseMove,
		updateIndicatorChartPart,
		upsertChartLsma,
		upsertChartMa,
	} from './FudaChartApi'

	Chart.register(CandlestickElement, CandlestickController, zoomPlugin, ...registerables)

	let candleChart: Chart
	let candleCanvas: HTMLCanvasElement
	let indicatorChart: Chart
	let indicatorCanvas: HTMLCanvasElement

	let seuritySetting: SecuritySetting
	let subscription1: Unsubscriber
	let subscription2: Unsubscriber
	let subscription3: Unsubscriber
	$: indicatorYaxisState = $indicatorYaxisStore
	$: trendLineState = $trendLineStore

	onMount(() => {
		initializeTooltip()

		candleChart = new Chart(candleCanvas, CandleChartConfig)
		candleCanvas.addEventListener('mousemove', candleChartMousemove)

		//indicatorChart
		indicatorChart = new Chart(indicatorCanvas, IndicatorChartConfig)
		indicatorCanvas.addEventListener('mousemove', indicatorChartMousemove)

		console.log('Chart.instance', Chart.instances)
		// Implement any data update logic here if needed

		// 订阅 klineResultStore 存储
		subscription1 = klineResultStore.subscribe((state) => {
			if (state.klines && state.klines.length > 0) {
				// TODO: 好像没有订阅到？？？？
				console.log('(SecurityChart).onMount() state.klines', state.klines)
				resetKlines(state.klines)
			}
		})

		// 订阅 klineResultStore 存储
		subscription2 = indicatorYaxisStore.subscribe((state) => {
			let klineResultState = $klineResultStore

			if (klineResultState && klineResultState.klines && klineResultState.klines.length > 0) {
				// TODO: 好像没有订阅到？？？？
				console.log('(SecurityChart).onMount() indicatorYaxisStore', state)
				updateIndicatorChartParts(klineResultState.klines)
			}
		})

		// 订阅 trendLineStore 存储
		subscription3 = trendLineStore.subscribe((state) => {
			console.log('(SecurityChart).onMount() trendLineStore', state)
			if (state.lines.length > 0) {
				upsertChartTrendLine(candleChart, state.lines[0], 'y-price')

				candleChart.update('reset')
				candleChart.resetZoom('resize')
			}
		})
	})

	function indicatorChartMousemove(event: MouseEvent) {
		handleChartMouseMove(event, indicatorChart, tooltipElement)
	}

	function candleChartMousemove(event: MouseEvent) {
		handleChartMouseMove(event, candleChart, tooltipElement)
	}
	onDestroy(() => {
		candleCanvas.removeEventListener('mousemove', candleChartMousemove)
		indicatorCanvas.removeEventListener('mousemove', indicatorChartMousemove)
		if (candleChart) candleChart.destroy()
		if (indicatorChart) indicatorChart.destroy()
		// 销毁订阅
		if (subscription1) subscription1()
		if (subscription2) subscription2()
		if (subscription3) subscription3()
	})

	function resetKlines(klines: KlineFlat[]) {
		updateCandleChart(klines)

		updateIndicatorChartParts(klines)
	}

	function updateIndicatorChartParts(klines: KlineFlat[]) {
		indicatorChart.data.datasets = []

		for (const [index, item] of indicatorYaxisState.yaxisQueue) {
			updateIndicatorChartPart(indicatorChart, klines, item, `y${index}`)
		}

		indicatorChart.update()
		indicatorChart.update('reset')
		indicatorChart.resetZoom('resize')
	}

	function updateCandleChart(klines: KlineFlat[]) {
		// console.log('updateCandleChart before', candleChart.data.datasets)
		// update candle1Chart
		candleChart.data.datasets = []
		// 更新价格蜡烛图
		upsertChartPrice(candleChart, klines, 'y-price')
		// 更新移动平均线
		upsertChartMa(candleChart, klines, 'sma', 5, 0, 'y-price')
		upsertChartMa(candleChart, klines, 'sma', 10, 1, 'y-price')
		// 更新交易量图
		upsertChartVolume(candleChart, klines, 'y-volume')

		// 更新线性回归趋势线
		upsertChartLsma(candleChart, klines, 5, 0, 'y-price')
		upsertChartLsma(candleChart, klines, 10, 1, 'y-price')
		upsertChartLsma(candleChart, klines, 20, 2, 'y-price')
		// 更新手工趋势线
		// upsertChartTrendLine(candleChart, trendLineState.lines[0], 'y-price')

		candleChart.update('reset')
		candleChart.resetZoom('resize')
		console.log('updateCandleChart after', candleChart.data.datasets)
	}
	function updateIndicatorChartGroup(group: number) {
		// 更新图表 indicatorChart
		indicatorChart.data.datasets = []
		if (group == -1) {
			// group -1 Commonly Used Indicators
			setIndicatorChartYaxises(['ADX', 'SAR', 'BOLL', 'MACD'])
		} else if (group === 0) {
			setIndicatorChartYaxises(['ADX', 'AROON', 'ASO', 'BOLL'])
		} else if (group === 1) {
			setIndicatorChartYaxises(['CCI', 'CKO', 'CKS', 'CMF'])
		} else if (group === 2) {
			setIndicatorChartYaxises(['CMO', 'CPC', 'DCC', 'DPO'])
		} else if (group === 3) {
			setIndicatorChartYaxises(['EFI', 'EOM', 'EVL', 'FTF'])
		} else if (group === 4) {
			setIndicatorChartYaxises(['HMA', 'IKC', 'KAMA', 'KDJ'])
		} else if (group === 5) {
			setIndicatorChartYaxises(['KNC', 'KST', 'KVO', 'MACD'])
		} else if (group === 6) {
			setIndicatorChartYaxises(['MFI', 'MTI', 'PCS', 'RSI'])
		} else if (group === 7) {
			setIndicatorChartYaxises(['RVI', 'SAR', 'SEI', 'TDSI'])
		} else if (group === 8) {
			setIndicatorChartYaxises(['TRIX', 'TRSI'])
		}

		indicatorChart.stop()
		indicatorChart.update('reset')
		indicatorChart.resetZoom('resize')
	}

	let tooltipElement: HTMLDivElement // Bind this to your tooltip div

	function initializeTooltip() {
		if (!tooltipElement) {
			console.error('Tooltip element not bound properly')
			return
		}
	}
</script>

<div class="w-full h-full grid grid-cols-6 grid-rows-18">
	<div class="row-span-16 col-span-5 px-1 bg-gray-700 text-white flex flex-col">
		<div class="w-full h-2/3 relative">
			<button
				name="resetzoom"
				class="absolute top-1 left-0 border-solid border-orange-500 border bg-orange-500 text-white text-xs px-1"
				on:click={() => {
					candleChart.resetZoom('resize')
					indicatorChart.resetZoom('resize')
				}}
			>
				Reset Zoom
			</button>
			<canvas bind:this={candleCanvas}></canvas>
		</div>
		<div class="w-full h-1/3"><canvas bind:this={indicatorCanvas}></canvas></div>
	</div>

	<div class="row-span-16 col-span-1 bg-blue-500 py-1 overflow-auto flex flex-col">
		<Tabs
			tabStyle="underline"
			class="flex"
			activeClasses="px-1 pt-1 pb-2 text-primary-600 bg-gray-100  dark:bg-gray-800 dark:text-primary-500"
			inactiveClasses="px-1 pt-1 pb-2 text-gray-500  hover:text-gray-600 hover:bg-gray-50 text-white dark:hover:bg-gray-800 dark:hover:text-gray-300"
			contentClass="p-0 bg-gray-50  dark:bg-gray-800"
		>
			<TabItem open title="C1">
				<div class="flex flex-col w-full h-full relative overflow-x-auto">
					<IndicatorsCombination comb={1} />
				</div>
			</TabItem>
			<TabItem title="C2">
				<div class="flex flex-col w-full h-full relative overflow-x-auto">
					<IndicatorsCombination comb={2} />
				</div>
			</TabItem>
			<TabItem title="C3">
				<div class="flex flex-col w-full h-full relative overflow-x-auto">
					<IndicatorsCombination comb={3} />
				</div>
			</TabItem>
			<TabItem title="C4">
				<div class="flex flex-col w-full h-full relative overflow-x-auto">
					<IndicatorsCombination comb={4} />
				</div>
			</TabItem>
			<TabItem>
				<div slot="title" class="items-center"><UserCircleSolid size="md" class="w-4 h-4" /></div>
				<div class="flex flex-col w-full h-full relative overflow-x-auto">
					<SecuritySetting bind:this={seuritySetting} />
				</div>
			</TabItem>
			<TabItem title="TL">
				<div class="flex flex-col w-full h-full relative overflow-x-auto">趋势线</div>
			</TabItem>
		</Tabs>
	</div>
	<div class="row-span-1 col-span-6 bg-gray-200" id="tooltipElement" bind:this={tooltipElement}>
		text content
	</div>
	<div class="row-span-1 col-span-6 bg-orange-500">
		<Tabs
			tabStyle="underline"
			activeClasses="px-1 pt-1 pb-2 text-primary-600 bg-gray-100  dark:bg-gray-800 dark:text-primary-500"
			inactiveClasses="px-1 pt-1 pb-2 text-gray-500  hover:text-gray-600 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-300"
			contentClass="p-0 bg-gray-50  dark:bg-gray-800"
		>
			<TabItem open title="Commonly Used Indicators" on:click={() => updateIndicatorChartGroup(-1)}
			></TabItem>
			<TabItem title="Adx... " on:click={() => updateIndicatorChartGroup(0)}></TabItem>
			<TabItem title="Cci... " on:click={() => updateIndicatorChartGroup(1)}></TabItem>
			<TabItem title="Cmo... " on:click={() => updateIndicatorChartGroup(2)}></TabItem>
			<TabItem title="Efi... " on:click={() => updateIndicatorChartGroup(3)}></TabItem>
			<TabItem title="Hma... " on:click={() => updateIndicatorChartGroup(4)}></TabItem>
			<TabItem title="Knc... " on:click={() => updateIndicatorChartGroup(5)}></TabItem>
			<TabItem title="Mfi... " on:click={() => updateIndicatorChartGroup(6)}></TabItem>
			<TabItem title="Rvi... " on:click={() => updateIndicatorChartGroup(7)}></TabItem>
			<TabItem title="Trix... " on:click={() => updateIndicatorChartGroup(8)}></TabItem>
			<TabItem title="Comb 1" on:click={() => updateIndicatorChartGroup(8)}></TabItem>
			<TabItem title="Comb 2" on:click={() => updateIndicatorChartGroup(8)}></TabItem>
			<TabItem title="Comb 3" on:click={() => updateIndicatorChartGroup(8)}></TabItem>
			<TabItem title="Comb 4" on:click={() => updateIndicatorChartGroup(8)}></TabItem>
		</Tabs>
	</div>
</div>
